import { FunctionComponent, useEffect, useRef, useState } from "react"
import Style from "./index.less"
import BScroll from '@better-scroll/core'
import { Stepper, Badge } from 'antd-mobile'
import { ISell } from "../../index"
import { BScrollConstructor } from "@better-scroll/core/dist/types/BScroll"


export interface ISellProps {
    data: ISell;
    onChange?: (e: ISell) => void
}


const Sell: FunctionComponent<ISellProps> = (props) => {
    const { data, onChange } = props;
    const tempData = useRef(props.data);
    const menuRef = useRef<HTMLDivElement>(null)
    const menuGoodRef = useRef<HTMLDivElement>(null)
    const currAct = useRef<number>(0);
    const clickStatus = useRef<boolean>(false)
    const scroll = useRef<BScrollConstructor | null>(null);
    let goodScroll = useRef<BScrollConstructor | null>(null);

    const BadgeNums: FunctionComponent<{ index: number }> = (props) => {
        const count = data[props.index].foods.reduce((total, item) => total + item.nums, 0)
        return (
            count ? <Badge content={count}>{data[props.index].name}</Badge> : <>{data[props.index].name}</>
        )
    }


    const selectMenu = (index: number, d?: any, opt = false) => {
        if (!d) {
            d = data;
        }
        // opt为false表示点击
        if (!opt) {
            clickStatus.current = true
        }
        if (menuRef.current && menuGoodRef.current) {
            scroll.current?.scrollToElement(menuRef.current.children[0].children[index] as any, 300, false, true)
            if (!opt) goodScroll.current?.scrollToElement(menuGoodRef.current.children[0].children[index] as any, 300, false, 0)
        }
        if (currAct.current !== index) {
            currAct.current = index;
            onChange?.(d.map((item: ISell[0], i: number) => ({
                ...item,
                current: index == i
            })))
        }
    }


    useEffect(() => {
        const wrapper = menuRef.current, goodWrapper = menuGoodRef.current
        scroll.current = wrapper ? new BScroll(wrapper, { click: true }) : null;
        const tops = Array.from(goodWrapper?.children[0].children as any).map((item: any) => -1 * item.offsetTop)
        goodScroll.current = goodWrapper ? new BScroll(goodWrapper, { click: true, probeType: 3 }) : null;
        goodScroll.current?.on('scroll', (pos: any) => {
            if (clickStatus.current) return;
            let { y } = pos, index = 0
            for (let i = 1; i < tops.length; i++) {
                if (y < tops[i - 1] && y > tops[i]) {
                    index = i - 1;
                    break;
                }
            }
            if (y < tops[tops.length - 1]) {
                index = tops.length - 1;
            }
            if (y >= tops[0]) {
                index = 0;
            }
            selectMenu(index, tempData.current, true)
        })
        goodScroll.current?.on("scrollEnd", () => {
            clickStatus.current = false;
        })
    }, [])

    useEffect(() => {
        // 更新缓存
        tempData.current = data;
    }, [data])

    return (
        <>
            <div className={Style.index_body_menu} ref={menuRef}>
                <ul className={Style.index_body_menu_inner}>
                    {
                        data.map((item, index) => (
                            <li onClick={() => selectMenu(index)} className={`${Style.index_body_menu_inner_li} ${item.current ? Style.current : null}`} key={`menu_${index}`}>
                                <BadgeNums index={index} />
                            </li>
                        ))
                    }
                </ul>
            </div>
            <div className={Style.index_body_content} ref={menuGoodRef}>
                <ul className={Style.body_wrapper}>
                    {
                        data.map((item, index) => (
                            <li key={`menu_li_${index}`} className={Style.body_unit}>
                                <div className={Style.body_unit_title}>{item.name}</div>
                                {
                                    item.foods.map((good, g_index) => (
                                        <div key={`menu_li_${index}_${g_index}`} className={Style.body_unit_content}>
                                            <div className={Style.unit_img}>
                                                <img src={good.image} />
                                            </div>
                                            <div className={Style.uni_info}>
                                                <div className={Style.uni_info_title}>{good.name}</div>
                                                <div className={Style.uni_info_extra}>
                                                    <span>月售{good.sellCount}份</span>
                                                    <span>好评率{good.rating}%</span>
                                                </div>
                                                <div className={Style.uni_info_buy}>
                                                    <div className={Style.uni_info_buy_price}>￥{good.price}</div>
                                                    <div className={Style.uni_info_buy_step}>
                                                        {
                                                            good.nums ? <Stepper
                                                                value={data[index].foods[g_index].nums}
                                                                onChange={value => {
                                                                    onChange?.(data.map((m, i) => {
                                                                        m.foods = m.foods.map((g, j) => {
                                                                            if (i == index && j == g_index) g.nums = value
                                                                            return g
                                                                        })
                                                                        return m
                                                                    }))
                                                                }}
                                                            /> : <div className={Style.step} onClick={() => {
                                                                const _data: ISell = JSON.parse(JSON.stringify(data))
                                                                _data[index].foods[g_index].nums += 1;
                                                                onChange?.(_data)
                                                            }}>+</div>
                                                        }
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    ))
                                }
                            </li>
                        ))
                    }
                </ul>
            </div>
        </>
    )
}

export default Sell